// check if voting is allowed
function voteAllowed(id) {
	var canvote = true;
	var voted = $.cookie("v");
	if (voted!=null) {
		voted = voted.split("|");
		for (i=0;i<voted.length;i++){
			if (voted[i]==id)
				canvote=false;
		}
	}
	return canvote;
}

// generate vote icon
var votedHTML = "Voted!";
var votedClicked = false;

function voteLink(id,userid,fbid,label1,label2) {
	if (userid=="" || voteAllowed(id))
		document.write(label1);
	else
		document.write(label2);

	votedHTML = label2;
}

function voteClick(id,userid,isFacebook) {
	if (!voteAllowed(id)) {
		alert("You have already voted for this");
		return;
	}
	
	if (votedClicked) {
		return;
	}
	votedClicked = true;
	$(".vote_star").hide();
  $(".voteSpinner").show();
	$("#big_vote_btn_text").hide();

	if (userid=="") {
		window.location = "user_login?msg=Please%20login%20to%20continue&nexturl="+location.href;
	}
// * disable FB
//	else if (isFacebook=='') {
//		sendVote(id,userid);
//	}
//	else {
//    	facebook_prompt_permission('publish_stream', function() { sendVote(id,userid); });
//	}
	else {
    	sendVote(id,userid);
	}

	if ($.query.get('recommended')) {
		ga_track('Recommendations', 'voted', id);
	}

	ga_track('Stories', 'Vote', id);
}

function sendVote(id,userid) {
	$.get("/api/vote.php?id="+id+"&userid="+userid, function(data) {done(id,data);});
}

function done(id, response) {
	// add to cookie to track vote
	var voted = $.cookie("v");
	if (voted!=null) {
		voted = voted + "|" + id;
		$.cookie("v", voted, { expires: 7300, domain: COOKIE_DOMAIN });
	}
	else {
		$.cookie("v", id, { expires: 7300, domain: COOKIE_DOMAIN });
	}
  $(".voteSpinner").hide();
	$(".vote_star").show();
	$(".vote_star").attr("src", $(".vote_star").attr("id"));
	$("#big_vote_btn_text").html(votedHTML);
	$("#big_vote_btn_text").show();
	$('.story_stat_votes').html($('.story_stat_votes').attr("id"));
}
